import 'package:file_selector/file_selector.dart' as fs;
import 'dart:io' show Platform;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/music_player_service.dart';
import '../widgets/mini_player_widget.dart';
import '../widgets/player_sheet_widget.dart';

import '../models/song.dart';
import '../services/playlist_management_service.dart';

class PlaylistDetailScreen extends StatefulWidget {
  final String playlistId;
  const PlaylistDetailScreen({super.key, required this.playlistId});

  @override
  State<PlaylistDetailScreen> createState() => _PlaylistDetailScreenState();
}

class _PlaylistDetailScreenState extends State<PlaylistDetailScreen> {
  String _name = '';
  List<Song> _songs = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    final p = await PlaylistManagementService.getPlaylistById(widget.playlistId);
    if (!mounted) return;
    setState(() {
      _name = p?.name ?? '';
      _songs = p?.songs ?? [];
      _loading = false;
    });
  }

  Future<void> _rename() async {
    final controller = TextEditingController(text: _name);
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('重命名歌单'),
          content: TextField(
            controller: controller,
            decoration: const InputDecoration(hintText: '新的名称'),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
            FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('确定')),
          ],
        );
      },
    );
    if (ok == true) {
      final name = controller.text.trim();
      if (name.isEmpty) return;
      await PlaylistManagementService.renamePlaylist(widget.playlistId, name);
      await _load();
    }
  }

  Future<void> _delete() async {
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('删除歌单'),
          content: Text('确定删除“$_name”吗？此操作不可恢复。'),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
            FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('删除')),
          ],
        );
      },
    );
    if (ok == true) {
      await PlaylistManagementService.deletePlaylist(widget.playlistId);
      if (mounted) Navigator.pop(context);
    }
  }

  Future<void> _export() async {
    try {
      if (Platform.isAndroid || Platform.isIOS) {
        final dir = await getTemporaryDirectory();
        final tempPath = '${dir.path}/${_name}_export.json';
        final path = await PlaylistManagementService.exportPlaylistToFile(
          id: widget.playlistId,
          filePath: tempPath,
        );
        await Share.shareXFiles([XFile(path)], text: '分享“$_name”歌单文件');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已导出并打开系统分享面板')),
          );
        }
      } else {
        const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
        final location = await fs.getSaveLocation(
          acceptedTypeGroups: const [typeGroup],
          suggestedName: '${_name}_export.json',
        );
        if (location == null) return;
        final path = await PlaylistManagementService.exportPlaylistToFile(
          id: widget.playlistId,
          filePath: location.path,
        );
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已导出到: $path')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导出失败: $e')),
        );
      }
    }
  }

  Future<void> _import() async {
    try {
      const typeGroup = fs.XTypeGroup(label: 'JSON', extensions: ['json']);
      final file = await fs.openFile(acceptedTypeGroups: const [typeGroup]);
      if (file == null) return;
      final count = await PlaylistManagementService.importPlaylistFromFile(
        id: widget.playlistId,
        filePath: file.path,
      );
      await _load();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已从 ${file.path} 导入 $count 首到“$_name”')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_name.isEmpty ? '歌单详情' : _name),
        actions: [
          IconButton(onPressed: _rename, icon: const Icon(Icons.edit), tooltip: '重命名'),
          IconButton(onPressed: _delete, icon: const Icon(Icons.delete_outline), tooltip: '删除'),
        ],
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
                  child: Row(
                    children: [
                      Text(
                        '共 ${_songs.length} 首',
                        style: const TextStyle(fontSize: 14, color: Colors.black54),
                      ),
                      const Spacer(),
                      GestureDetector(
                        onTap: _export,
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.blue.withOpacity(0.08),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: Colors.blue.withOpacity(0.3)),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.download, size: 16, color: Colors.blue[600]),
                              const SizedBox(width: 4),
                              Text('导出', style: TextStyle(fontSize: 12, color: Colors.blue[600], fontWeight: FontWeight.w500)),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      GestureDetector(
                        onTap: _import,
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.blue.withOpacity(0.08),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: Colors.blue.withOpacity(0.3)),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.upload, size: 16, color: Colors.blue[600]),
                              const SizedBox(width: 4),
                              Text('导入', style: TextStyle(fontSize: 12, color: Colors.blue[600], fontWeight: FontWeight.w500)),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const Divider(height: 1),
                Expanded(
                  child: _songs.isEmpty
                      ? const Center(child: Text('此歌单内暂无歌曲'))
                      : ListView.separated(
                          itemBuilder: (context, index) {
                            final s = _songs[index];
                            return ListTile(
                              leading: Text('${index + 1}'),
                              title: Text(s.name),
                              subtitle: Text('${s.artistsString}${s.album.isNotEmpty ? ' · ${s.album}' : ''}'),
                              onTap: () {
                                final svc = Provider.of<MusicPlayerService>(context, listen: false);
                                svc.setPlaylist(_songs, startIndex: index);
                              },
                            );
                          },
                          separatorBuilder: (_, __) => const Divider(height: 1),
                          itemCount: _songs.length,
                        ),
                ),
              ],
            ),
      // 底部迷你播放器：有歌曲播放时显示
      bottomNavigationBar: Consumer<MusicPlayerService>(
        builder: (context, svc, child) {
          if (svc.currentSong == null) return const SizedBox.shrink();
          return MiniPlayerWidget(onTap: _showPlayerSheet);
        },
      ),
    );
  }

  void _showPlayerSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      constraints: const BoxConstraints(
        maxWidth: double.infinity,
        maxHeight: double.infinity,
      ),
      useSafeArea: true,
      builder: (context) => const PlayerSheetWidget(),
    );
  }
}
